//Ext.BLANK_IMAGE_URL=CFG.app_ctx+"ext/resources/images/default/s.gif";
var bReadyOk=0;
//var winsvg;
var THLayout = Class(object, {
    Create: function(items){
    	this.version ='2010.12';
        this.items=items;
        this.trees={};
        this.ws = null;
        this.subscribe_cout={};
        this.attach_sid_dom={};
        this.attach_dom_sid={};
        this.verify=false;
        this.pos_left=0;
        this.pos_top=0;
        this.pos_id=0;
        this.mtp={};
        this.close_other_tab=true;   
        this.b_debug=false;
    },

  send_subscribe:function(cns,action){
	this.ws.send_subscribe(cns,action);
  },
  send:function(data){
  	this.ws.send(data);
  },
  getws:function(url,con_span,cns){
  	if(this.ws){
  		return this.ws;
  	}
	var wsc = New(WSClient,[url,con_span,cns]);
	wsc.setevt("onclose",function(){
		layout.comet_fail();
	});
	wsc.setevt("onopen",function(){
		layout.comet_succ();
	});
	
	wsc.setfunc("PR_SYS_MSG",function(s){
		Bat.msgfmt(s.items.map);
	});
	wsc.setfunc("net.bat.task.Task",function(s){
		var items = s.items.map;
		if(items.fcur){
			Ext.MessageBox.updateProgress(items.fcur, items.info);
		}else{
			if(items.info){
				Ext.MessageBox.updateText(items.info);
			}
			//if(items.title){
			//	Ext.MessageBox.setTitle(items.title);
			//}
		}
	});
	wsc.connect();
	this.ws =wsc;  
	return wsc;
  },
  selectNode:function(title,treePath,attr){
  	//var tree = this.trees[treeId];
	var tree;
	//允许输入id
	tree = this.trees[title];
	if(!tree){
		for(var x in this.trees){
			if(this.trees[x].title==title){
				tree = this.trees[x];
				break;
			}
		}
	}
  	if(!tree) return false;
  	if(!attr) treePath = "/Root/"+treePath;
  	tree.selectPath(treePath,attr||"text",'/',function(bSuccess, oSelNode ){
  		if(bSuccess){
  			tree.expand();
  			tree.fireEvent("itemclick",tree,oSelNode);
  			return true;
  		} else return false;
  	}
  	);
  },
  onEditNotice:function(){
	var wp = Bat.dlgs["edit_notice"];
	if(!wp){
 		
	  var fm = new Ext.Panel({
    items: [{
    	id:'notice_content',
    	width:700,
    	height:250,
        xtype:'htmleditor',
        layout: 'fit',
        enableAlignments: false,
         plugins : [
	        	Ext.create('Ext.fucj.form.HtmlEditorImage'),
	        	Ext.create('Ext.fucj.form.HtmlEditorAttachment')
	        ],
        value:Ext.get("tabs_about").dom.innerHTML
    }]        
	});
    wp = new Ext.Window({
    	modal:true,
     	draggable:false,
    	resizable:false,
   		closeAction:'hide',
    	shadowOffset:15,
    	shadow: true,
        title: '编辑公告',
        width: 716,
        autoHeight:true,
        layout: 'form',
        buttonAlign:'center',
        items: fm,
		defaultButton:'id_ok',
        buttons: [{
        	//id:'id_ok',
            text: '确定',
            handler: function(){
            	//var hf = Ext.get('notice_content');
            	var hf = Ext.getCmp('notice_content');
            	//hack begin missing and position mistake
            	var bstr = '<!--NOTICE BEGIN-->';
            	var nc = hf.getValue();
            	if(nc.indexOf(bstr)!=0){
            		nc = bstr+nc.replace(bstr,'');
            	}
            	var ps = {'notice_content':nc};  
             	var req={"map":ps,"javaClass":"java.util.HashMap"};
			  jsonrpc.BH.handle(function(data,ex){
		   		if(Bat.outputEx(ex,'发送留言异常'))
		   			return;
			  	wp.hide();
			  	Ext.get("tabs_about").dom.innerHTML=hf.getValue();
			  layout.tabVersion.bHide=false;
			//  layout.tabPanel.unhideTabStripItem(this.tabVersion);
			 // layout.tabPanel.setActiveTab(layout.tabVersion.show());
			  },'N',req,'UMService'); 
            }            
        },{
            text: '取消',
            handler: function(){
            	wp.hide();
            }
        }],
        keys: [
        //回车确定
         /*   {stopEvent: true,
			 key: [Ext.EventObject.ENTER], handler: function() {
            	var btn_ok=wp.buttons[0];
            	btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok); 
               }
            }*/
        ]        
    });
	Bat.dlgs["edit_notice"]=wp;
	}
	wp.show();	
	return false;
  },
  onhelp:function(){
    var tabPanel=this.tabPanel;
   //	var hlp_url = CFG.base_url+"hlp/index.htm?kw="+tabPanel.getActiveTab().title;
   	var hlp_url = CFG.base_url+"cm/help/help.htm?kw="+tabPanel.getActiveTab().title;
   	if(!this.tabHelp){
		this.tabHelp= tabPanel.add({
			bodyStyle:'padding:10px;font-size:12px;',
            title: '在线帮助',
            iconCls: 'tabs',
            html: "<iframe style=\"border: 0px;\" width=\"100%\" height=\"100%\" id=\"ifm_hlp\"></iframe>",
           	closable:true,
            autoDestroy: false,
			autoScroll: true,
			bHide:true
        }).show();
       }
   	else{
		 this.tabHelp.bHide=false;
		// tabPanel.unhideTabStripItem(this.tabHelp);
		 this.tabHelp.tab.show();
		 tabPanel.setActiveTab(this.tabHelp);
   	}
	var ifm = Ext.get("ifm_hlp").dom.src=hlp_url;
	return false;
  },

  login:function(func_succ,user,pwd){
	 var loginfm = new Ext.form.FormPanel({
      baseCls: 'x-plain',
      bodyStyle: {
    	    //background: '#ffc',
    	    padding: '20px 20px 0px 20px'
    	},
      labelWidth: 80,
      items: [{
          xtype:'fieldset',
          padding:10,
          autoHeight:true,
          title: '',
           defaultType: 'textfield',
           defaults: {width: 300},
           items:[{
           	fieldLabel:Bat.info.usr_name,
           //allowBlank: false,
           	//mode:'local',
           	anyMatch:true,
           	//queryMode:'local',
           	name:'user',
           	valueField :'id',
          	value:user|| '',
          	width:280,
           	xtype:'combo',
           	listeners: {
                change: function(fld, newValue, oldValue, eOpts) {
                	var fm = fld.up('form');
                	var fld_pwd = fm.getForm().findField('pwd');
                	fld_pwd.setValue('');
                	fld_pwd.isValid(); 
                	console.log(fld_pwd);
                }
            },
            
            lazyInit:false,
           	emptyText :'请选择',
           	displayField:'name',
           	triggerAction:'all',
           	typeAhead :true,
           	minChars:1,
           	listConfig: {
			        getInnerTpl: function() {
			            return '<div data-qtip="{name}. {pyh}">{name} ({id})</div>';
			        }
			    },
           	store:{
		        fields: ['id','name','pyh'],
		        proxy: {
		           //异步获取数据，这里的URL可以改为任何动态页面，只要返回JSON数据即可
		            type: 'ajax',
		            url: CFG.app_ctx+"servlet/JSonBaseServlet?hql=select userId,name,namePyh from UUser where (status='1' or status is null)",
		         //    url: CFG.app_ctx+"servlet/JSonBaseServlet?hql=select userId,name,namePyh from UUser ",
		            reader: {
		                type: 'array',
		                root: 'list'
		            }
		        },
		        autoLoad: false
		    }
       },{
          fieldLabel: Bat.info.usr_pwd,
          msgTarget :'side',
          defaults: {width: 300},
          validator:function(value){
      		var fm = this.up('form');
      		var fld_user = fm.getForm().findField('user');
      		var val_user = fld_user.getValue();
      		if(!val_user)
      			return "请选择用户";
              var req={"map":{userId:val_user,pwd:this.getValue()},"javaClass":"java.util.HashMap"};
	            var data = jsonrpc.BH.handle('C',req,'UMService');                          	
      		var btn_ok = loginwin.down('button[id=login_id_ok]');
      		if(data){
      			btn_ok.enable();
      			return true;
      		}else{
      			btn_ok.disable();
          		return "密码不正确";
      		}
      },
          name: 'pwd',
          value: pwd||'',
          inputType: 'password'
      }]}, {
         listeners:{
        	'collapse':function(){
        		var fld_pwd2 = loginfm.getForm().findField('pwd2');
        		var fld_pwd1 = loginfm.getForm().findField('pwd1');
        		fld_pwd1.setValue(null);
        		fld_pwd2.setValue(null);
        	 loginwin.syncShadow();
        	},
        	'expand':function(){loginwin.syncShadow();}},
          xtype:'fieldset',
          checkboxName:'changepwd',
          checkboxToggle:true,
          title: '修改我的密码',
          collapsed: true,
          autoHeight:true,
          defaultType: 'textfield',
          defaults: {width: 300},
          padding:10,
          items :[{
                  fieldLabel: '新密码',
                  name: 'pwd1',              
                  inputType: 'password',
                  msgTarget :'side',
               	validator:function(val){
              		var btn_ok = loginwin.down('button[id=login_id_ok]');
              		var fld_pwd2 = loginfm.getForm().findField('pwd2');
             	  	if(fld_pwd2.isValid()){
  	            	  return true;
             	  	}
	            	else{
	            		return '密码输入不一致';  
	            	}
	            }	                                
              },{
                  fieldLabel: '确认新密码',
                  inputType: 'password',
                  msgTarget :'side',
                  name: 'pwd2',
             	validator:function(val){
              		var btn_ok = loginwin.down('button[id=login_id_ok]');
              		var fld_pwd1 = loginfm.getForm().findField('pwd1');
             	  	if(val==fld_pwd1.getValue()){
             	  		fld_pwd1.clearInvalid( );
             	  		return true;
             	  	}
	            	else{
	            		return '密码输入不一致';  
	            	}
	            }	                                
              }
           ]
      }]        
  });
    //form.render(document.body);
	//return;
	var h=window.innerHeight
	|| document.documentElement.clientHeight
	|| document.body.clientHeight;    
	var top = h/2-150;
    var loginwin = new Ext.Window({
    	style:'top:0px;opacity:0;',
    	draggable:false,
    	resizable:false,
    	//monitorResize:true,
    	//shadowOffset:35,
    	shadow: false,
   		//modal:true,
    	closable:false,
        title: '登录',
        width: 400,
        //height:200,
        autoHeight:true,
        layout: 'auto',
        plain:true,
        //bodyStyle:'padding:5px;background-image:url("icons/bg_login.png");',
        buttonAlign:'center',
        items: loginfm,
		defaultButton:'login_id_ok',
        buttons: [{
        	id:'login_id_ok',
            text: '确定',
            disabled:true,
            handler: function(){  
            	if(!loginfm.isValid())
            		return;
            	var ps = loginfm.getForm().getValues();
            		var butt=this;
                	loginwin.setTitle("正在登录,请稍等...");
            		if(ps.changepwd){ 
                		if(ps.pwd1!= ps.pwd2)
                	 		return false;
                	}else{
                		delete ps.pwd1;
                		delete ps.pwd2;
                	}
                	//Bat.gvs.wf_userName=ps.user;
                	ps.user =  loginfm.getForm().findField('user').getValue();
                	var req={"map":ps,"javaClass":"java.util.HashMap"};
    			  jsonrpc.BH.handle(function(data,ex){  				  
    		   		if(Bat.outputEx(ex,'用户登录异常')){     		   
    		   			loginwin.setTitle("登录失败,请检查用户名密码");
                		loginwin.down('button').enable();
    		   			return;
    		   		}
    		   		//根据获得的菜单权限组织菜单
    		   			layout.usr_info=ps;
    		   			layout.user_name = data[3];
    		   			layout.user_dpt = data[6];
    		   			layout.user_mnu = data[5];
    		   			layout.usr_grant=data;
    		   			layout.userid=data[4];
    		   		    Ext.create('Ext.fx.Anim', {
    		   		        target: loginwin,
    		   		        duration: 1000,
    		   		        from: {
    		   		            opacity: 1,       // Transparent
    		   		            top: top
    		   		        },
    		   		        to: {
    		   		        	opacity: 0, //end width 300
    		   		        	top:0
    		   		         },
    		   		      listeners:{
    		   		    	afteranimate:function(ani,start_time,opt){
    		   		    		loginwin.hide(); 
    		   		    	}
    		   		      }
    		   		    });
    		   		    
    		   			//loginwin.hide();]
    		   		    if(data.length==5){
    		   		    	data[5]='';
    		   		    }
    					func_succ(data);
    					butt.disable();
    			  },'L',req,'UMService');  
                      	
            }            
        }],
        listeners: {
            afterRender: function(thisForm, options){
                this.keyNav = Ext.create('Ext.util.KeyNav', this.el, {                    
                    enter: function(){
                    	var btn_ok = loginwin.down('button[id=login_id_ok]');
                    	btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok); 
                    	//console.log(btn_ok);
                    },
                    scope: this
                });
            }
        }
    });

    Ext.create('Ext.fx.Anim', {
        target: loginwin,
        duration: 1000,
        from: {
            opacity: 0,       // Transparent
            top: 0
        },
        to: {
        	opacity: 1, //end width 300
        	top:top
         }
    });
    
    
   loginwin.show();
    loginfm.isValid();
  },
  dowithState:function(s){
  	if(s.cn=="Task")
  	  Bat.showProgress(s);
  	if(s.cn=="MMessage" && s.action=='A' ){
  	 	var pm = s.items.map;
  	 	if(pm && pm.stype!='SYS_RECOVER')
  	 		Bat.msgfmt(pm);
  	}
  	//if(s.cn=="MHeart")
  	//	alert(s.items.map.tm.time);
  },
  addTask:function(s){
  	
  },
  updateTask:function(s){
  	
  },
  removeTask:function(s){
  	
  },
  comet_succ:function(e){
  	if(layout.verify){
	  var req={"map":{handleKey:layout.usr_grant[2]},"javaClass":"java.util.HashMap"};
	  jsonrpc.BH.handle(function(data,ex){
   		if(data[0]==0 && !ex){
   			ex={msg:'会话已失效，请重新登录'};
   		}
   		if(Bat.outputEx(ex,'恢复登录失败'))
   			return;
	  },'V',req,'UMService');            	 		
  	}
  	if(Ext.MessageBox.isVisible())
  		Ext.MessageBox.hide();
  	var mi = this.tbar.queryById("mi_comet");
  	mi.setText("已连接");
  	mi.setIconCls("link");  	
  },
  comet_connect:function(e){
  	var mi = this.tbar.queryById("mi_comet");
  	mi.setText("连接中");
  	mi.setIconCls("link");
  },
  comet_fail:function(e){
  	var mi = this.tbar.queryById("mi_comet");
  	mi.setText("未连接");
  	mi.setIconCls("link_break");
  	this.verify=true;
    Ext.MessageBox.show({
      closable:false,
      modal:true,
      title: '服务失联了:(',
      msg: '<b>由于:</b><font color="red">网络繁忙或服务关闭</font>,暂无服务响应。<br><b>请您关闭浏览器并稍后尝试重新连接。</b>'
   });
  },
  /**
   * 根据vn,kn,kv直接打开并渲染详细页
   * @param {} vn
   * @param {} kn
   * @param {} kv
   */
  renderDetailByKey:function(vn,kn,kv,tn){
  	//TODO 复用
  	
	if(typeof kv == 'string' && kv[0]!= "'"){
			kv = "'"+kv+"'";
	}
	
	var vwd = BView.viewMap[vn];
  	var vw = New(BView,[vwd]);
	vw.req.map.method = 'G';
	var kn=kn||'id';
	if(vw.req.map.cns.length>1 && kn.indexOf('.')==-1){
		kn='A.'+kn;
	}
	var hql = vw.req.map.hql;
	var pos_ordby = hql.toLowerCase().indexOf('order by');
	if(pos_ordby!=-1){
		hql = hql.substring(0,pos_ordby);
	}
	var pos = hql.toLowerCase().indexOf('where');
	if(pos==-1){
		 vw.req.map.hql=hql+' where '+kn+'='+kv;
	}else{
		 vw.req.map.hql=hql+' and '+kn+'='+kv;
	}
	
	jsonrpc.BH.handle(function(data, ex) {
		if (Bat.outputEx(ex, '请求记录数据异常'))
			return;
			var obj;
			if(data.length>1){
			 	obj = data[1];
			}else{
				obj = data[0];
				obj.action='A';
			  	vw.child_views=false;
			  	vw.rel_views=false;
			}
			if(vwd.func_item){
				vwd.func_item(vw,obj);
			}
			var bui = vwd.bui;
			if(!bui){
				bui=New(BatUI,[vw,layout.tabPanel,vwd.cn||vn]);
				vwd.bui=bui;
			}
			Bat.setIts(obj);
			if(vw.gridTitle){
			   obj.gridTitle=vw.gridTitle;
			}
			bui.renderDetailPanel(obj,tn);
		}, 'G', vw.req, '');
  },
  renderGridByNode:function(node){
	var vn=node.vn||node.get('vn');	
	if(!vn){
		return;
	}
	var bui = node.bui;
	if(!bui){
		var vw = New(BView,[BView.viewMap[vn]]);
		if(node.nc.func_vw)
			node.nc.func_vw(vw);
		var title = node.getPath('text').substr(6);
		bui = New(BatUI,[vw,this.tabPanel,title]);
		var cd = this.tabPanel.add({
			prev_hide:true,
			title : title,
			closable : true,
			autoDestroy : false,
			autoScroll : false,
			layout:'fit',
			//bodyStyle: 'background-color:transparent',
			items: {
			    title: 'Fit Panel',
			    header:false,
			    xtype:'bat_grid',
			    border: false,
			    ui:bui
			}
		});
		cd.showBy(node);
		cd.uiGrid=bui;
		bui.tabGrid = cd;		
		node.bui = bui;
	}else{
		if(node.nc.func_vw)
			node.nc.func_vw(bui.view);
	}
	bui.renderGridTab();
  },    
    
  buildNode:function(pn,nc){
	if(!pn || !nc)
	  return;	
	if(typeof nc=='string')
	  nc = {text:nc};
	//禁用qtip
	if(nc.qtip)
		delete nc.qtip;
	var cn = pn.appendChild(nc);
  	cn.nc=nc;
  	cn.vn=nc.vn;
	if(nc.ns){
		for(var i=0; i<nc.ns.length; i++){
			this.buildNode(cn,nc.ns[i]);
		}  	
	}else{
		cn.set('leaf',true);
	}
	return cn;
  },
  buildTree:function(nn,id,title,iconCls,func_click){
	var root = {
		text:"Root", 
		allowDrag:false,
		allowDrop:false
	};
   var tree = new Ext.tree.Panel( {
		id:id,
		markDirty :false,
		useArrows: true,
		title:title,
		iconCls:iconCls,
		root:root,
		animate:true, 
		containerScroll: true,
		rootVisible:false
	});
	for(var i=0;i<nn.length;i++)
	  	this.buildNode(tree.getRootNode(),nn[i]);
	if(func_click)
		tree.on("click",func_click,this);
	else{
	  //var me=this;
	  tree.on('itemclick',function(self, store_record, html_element, node_index, event){
	  	if(store_record.nc.detil){
	  	   layout.renderDetailByKey(store_record.vn,false,1);
	  	}else{
	  	   //  console.log(self);
		   this.renderGridByNode(store_record);	
	  	}	
	},this);
	}
	//tree.expandAll();
	this.trees[id]=tree;
	tree.expandAll();
	return tree;
  },
 buildToolbar:function(){
	var b_not_admin = (layout.user_mnu.indexOf('系统管理')==-1);
 	var svs=[];
 	for(var i=10; i<100; i+=5){
 		svs[svs.length]=[i+"",i];
 	}
    var combo = new Ext.form.ComboBox({
        hideLabel: true,
        store: new Ext.data.SimpleStore({
			fields : ['txt', 'val'],
			data :svs
		}),
		displayField : 'txt',
		valueField : 'val',
		typeAhead : true,
		mode : 'local',
		triggerAction : 'all',
		emptyText : 'Top...',
		selectOnFocus : true,
		width:100,
		value:gridPagePer,
		listeners:{
		  scope:this,
         'select': function(co,rec,index){
        	gridPagePer=co.getValue();
         }
    	}
    });
		var ths=["classic","gray","access","neptune"];
		var thsItems=[];
		for(var i=0; i<ths.length; i++){
			thsItems[thsItems.length]={checked: false,text:ths[i],group:"theme",
				checkHandler:function(item, checked){
					if(checked){
						//var name = select[select.selectedIndex].value;
        				setActiveStyleSheet(item.text);
        				
					}
				}
		  }
		}
		var bk_url = CFG.base_url+"th/icons/head.jpg";
            
		return {
		//	margin:'40 5 0 10',
		style: 'padding-top:15px;padding-right:15px;background-color: transparent;', 
	 	region:'north',
	 	height: 60,
	 	id:'toolbar-left',
	 	items:[
		'->',
	 		{
		 id:'mi_save',
         cls: 'x-btn-text-icon',
         icon: 'icons/disk.png',
		 text:'保存',
		 hidden:true,
		 //scope:this,
		 handler:function(b,e){
		 	var tp = layout.tabPanel;
		 	var ap = tp.getActiveTab();
		 	var uidt = ap.uiDetail;
		 	//110111 "this" change after remove ap
		 	if(!uidt.validateForm()){
		 		return false;
		 	}
	 		uidt.save();
	 		if(layout.close_other_tab){
	           ap.bHide=true;
	           ap.tab.hide();	
	           if(ap.tn){
	        	   layout.selectNode(ap.tn.id,ap.tn.path);
	           }else{
		           var tab_prev = ap.prev;
		           if(tab_prev){
			           tab_prev.bHide=false;
			           tab_prev.tab.show();
			    	   tp.setActiveTab(tab_prev);
		           }
	           }
	 		}else{	 		
				tp.remove(ap,false);
			 	if(uidt.pui){
			 		tp.setActiveTab(uidt.pui.tabDetail);
			 	}else tp.setActiveTab(uidt.tabGrid);
		 }
		}
		},{
		 id:'mi_prev',
         cls: 'x-btn-text-icon',
         icon: 'icons/arrow-up.gif',
		 text:'上一条',
		 hidden:true,
		 //scope:this,
		 handler:function(b,e){
			var tb = layout.tbar;
		 	var tp = layout.tabPanel;
		 	var ap = tp.getActiveTab();
		 	var ui = ap.uiDetail;
		 	var objs = ui.objs;
		 	var objcur=ui.obj_detail;
		 	var len = objs.length;
		 	for(var i=0; i<len; i++){
		 		if(objcur==objs[i]){
		 			if(i>0){
		 				ui.setObjDetail(objs[i-1]);
		 			}
		 			if(i==0){
		 				tb.down("#mi_prev").disable();
		 			}
		 			tb.down("#mi_next").enable();
		 			break;
		 		}
		 	}		 	
		}
		},{
		 id:'mi_next',
         cls: 'x-btn-text-icon',
         icon: 'icons/arrow-down.gif',
		 text:'下一条',
		 hidden:true,
		 //scope:this,
		 handler:function(b,e){
		 	var tb = layout.tbar;
		 	var tp = layout.tabPanel;
		 	var ap = tp.getActiveTab();
		 	var ui = ap.uiDetail;
		 	var objs = ui.objs;
		 
		 	var objcur=ui.obj_detail;
		 	var len = objs.length;
		 	for(var i=0; i<len; i++){
		 		if(objcur==objs[i]){
		 			if(i<len-1){
		 				ui.setObjDetail(objs[i+1]);
		 			}
		 			if(i==len-2){
		 				tb.down("#mi_next").disable();
		 			}
		 			tb.down("#mi_prev").enable();
		 			break;
		 		}
		 	}		 	
		}
		},
		{
			 id:"mi_comet",
			 disabled:true,
			 hidden:true,
			 text:'未连接',
			 iconCls: 'link_break',
			 handler:function(btn){
			 	Bat.comet.setconnect(false);
			 	var mi = this.tbar.findById("mi_comet");
 				mi.setText("未连接");
				mi.setIconClass("link_break");
			  },scope:this
			},{
		    text:layout.user_name,
         	cls: 'x-btn-text-icon-transparent',
         	icon: 'icons/user.png',
            menu: {
			items: [
			    //combo,
				{ text: '主题风格',
				hidden:true,
                icon: 'icons/style.png',                
                menu: {        // <-- submenu by nested config object
                    items:thsItems
                }
            },
            { text:'在线帮助',
              hidden:true,
			 icon: 'icons/book_open.png',
				handler:function(btn){
					return layout.onhelp();
			  },scope:this
            },{				
			 text:'公告栏',
			 hidden:true,
			 icon: 'icons/star.png',
				handler:function(btn){
					
				  this.tabVersion.bHide=false;
				  //this.tabPanel.unhideTabStripItem(this.tabVersion);
				  this.tabVersion.tab.show()
				  this.tabPanel.setActiveTab(this.tabVersion);
				 if(layout.user_mnu.indexOf("系统管理")!=-1){
					return layout.onEditNotice();
				 }
			  },scope:this
			},{				
			 text:'状态图',
			 hidden:true,
			 //hidden:b_not_admin,
			 icon: 'icons/asterisk_orange.png',
				handler:function(btn){
				 BView.openTabpanel("arbor","发布-订阅状态图","../ol/arbor.html");
			  },scope:this
			},
			{text:'关于',
			 id:'mi_about',
			 icon: 'icons/information.png',
				handler:function(){Ext.MessageBox.show({
				title:'关于', 
				icon: Ext.MessageBox.INFO,
				animEl:'mi_about',
				msg:'<p align=\'center\'>'+CFG.app_name+CFG.about+'</p>',
				buttons: Ext.MessageBox.OK,
				width:220
			});
			}			
			},{
				 id:'mi_exit',
		         cls: 'x-btn-text-icon',
		         icon: 'icons/quit.png',
				 text:'注销',
				 handler:function(){
				 	Ext.MessageBox.confirm("退出确认","您确定要退出系统吗？",function(btn){
				 		if(btn=="no")
				 			return;
				 		//window.location.href=window.location.href;
				 		//clear cookie	
				 		Cookies.clear('COOKIE_OBJ');
						Cookies.clear('COOKIE_FUNC');
						Cookies.clear('COOKIE_USER');
						Cookies.clear('COOKIE_ROLE');
						Cookies.clear('COOKIE_UN');
						Cookies.clear('COOKIE_USER_ID');
						Cookies.clear('COOKIE_ORGID');
						
						window.removeEventListener('beforeunload', window_beforeUnload);
					  var req={"map":layout.usr_info,"javaClass":"java.util.HashMap"};
					  jsonrpc.BH.handle(function(data,ex){
				   		if(Bat.outputEx(ex,'用户退出异常'))
				   			return;	
				   		document.location='/zpn/servlet/authenticate?cmd=logout';
					  },'O',req,'UMService');            	
				 	});
				 }
				}]}}]};
	},
	hideDetailBtns:function(){
		var its_tbar = this.tbar.items;
		for(var i=0; i<its_tbar.length; i++){
			var ci = its_tbar.items[i];
			//避免删除右边栏
			if(ci.only_detail)
				ci.hide();
		}
	},
	attachDom:function(sid,domId){
		var old_sid = this.attach_dom_sid[domId];
		if(old_sid){
			//原来sid数组无效
			delete this.attach_sid_dom[old_sid];
			this.getAttachDom(old_sid);
		}
		this.attach_dom_sid[domId]=sid;
		//新sid数组也无效
		delete this.attach_sid_dom[sid]
		this.getAttachDom(sid);
		return domId;
	},
	getAttachDom:function(sid){
		var domIds = this.attach_sid_dom[sid];
		if(domIds){
			return domIds;
		}else{
			var dids = [];
			for(x in this.attach_dom_sid){
				if(this.attach_dom_sid[x]==sid){
					dids[dids.length]=x;
				}
			}
			this.attach_sid_dom[sid]=dids;
			return dids;
		}
	},
	show_subscribe:function(prs){
		var prs_send=[];
		for(var i=0; i<prs.length; i++){
			var pr = prs[i];
			var pr_count=this.subscribe_cout[pr];
			if(!pr_count){
				this.subscribe_cout[pr] =1;
				prs_send[prs_send.length]=pr;
			}else{
				this.subscribe_cout[pr] = pr_count++;
			}			
		}
		if(prs_send.length>0){
			this.send_subscribe(prs_send,'A');
		}
	},
	hide_subscribe:function(prs){
		if(!prs){
			return false;
		}
		var prs_send=[];
		for(var i=0; i<prs.length; i++){
			var pr = prs[i];
			var pr_count=this.subscribe_cout[pr];
			if(!pr_count){
				this.subscribe_cout[pr] = pr_count--;
				if(this.subscribe_cout[pr]==0){
					prs_send[prs_send.length]=pr;
				}
			}			
		}
		if(prs_send.length>0){
			this.send_subscribe(prs_send,'R');
		}
	},
	show:function(){
       var tabPanel=new Ext.TabPanel({
    	   //icon:'icons/play.png',
    	   minTabWidth:120,
    	   headerPosition: 'bottom',
    	  // tabPosition: 'bottom',
    	    //plain:this.close_other_tab,
    	   	plain: true,
       		autoDestroy:false,
        	tps:[],
        	show_tabs:{},
            region:'center',
            id:'center',
            enableTabScroll:true,//wjh
            defaults: {autoScroll:true},//wjh                    
            deferredRender:false,
            plugins: new Ext.ux.TabCloseMenu(),
           listeners:{
               'afterrender': function(panel) {
                   var bar = panel.tabBar;
                   bar.insert(2, [{
                       xtype: 'component',
                       flex: 1
                   }, {
                	   margin:'3 50 0 0',
                       xtype: 'button',
                      
                       id: 'btn_return',
                       text: '返回',
                       cls: 'x-btn-text-icon',
                       icon: '../cm/icons/back16.png',
                       hidden:true,
                       listeners:{
                       'click': function(btn,e) {
                    	   var tp = layout.tabPanel;
                    	   var ap = tp.getActiveTab();
                    	   var ui = ap.uiGrid||ap.uiDetail;
				           ap.bHide=true;
				           ap.tab.hide();	
				           if(ui && ui.view){
	                    	   var func_return = ui.view.funcs.func_return;
	                    	   if(func_return){
	                    	   		func_return(ap);
	                    	   		return;
	                     	   }
				           }
				           var tab_prev = ap.prev;
				           //隐藏本按钮
				           if(!tab_prev.prev || tab_prev.prev_hide){
				        	   btn.hide();
				           }else{
				        	   btn.show();
				           }
				           tab_prev.bHide=false;
				           tab_prev.tab.show();
                    	   tp.setActiveTab(tab_prev);
                       }                       }

                   }]);
               },        	   
        	   
            "contextmenu":function(tabs,tab,e){
              tabs.tabmenu=tab;
              var menu = tabPanel.cmenu;
              if(!menu){
				menu=new Ext.menu.Menu({items:[{
				text:"关闭其他页",
				handler:function(){
					tabs.setActiveTab(tabs.tabmenu);
					//循环遍历
					tabs.items.each(function(item){
					if(item!=tabs.tabmenu){
				        tabs.hideTabStripItem(item.hide());
				        item.bHide=true;
					}
					});
				 }
				},{
				text:"关闭所有页",
				handler:function(){
					//循环遍历
					tabs.items.each(function(item){
				        tabs.hideTabStripItem(item.hide());
				        item.bHide=true;
					});
				 }
				}]});
				tabPanel.cmenu=menu;
              }
				//显示在当前位置
				menu.showAt(e.getPoint()); 
			  }
            }
        });
       this.tabPanel=tabPanel;
       tabPanel.on('beforeadd', function(tabs, tab) {
    	   tab.closeAction='hide';
       		if(tabs.tps)
       	 		tabs.tps[tabs.tps.length]=tab;
       	 	else
       	 		tabs.tps=[];
			if(layout.close_other_tab){   
				tab.closable =false;
				tab.prev = tabs.getActiveTab(); 
				tab.on('beforeshow', function(tab) {
					 var tabs = layout.tabPanel;
					  var items = [];
				      tabs.items.each(function(item){
				           // if(item.closable){
				                if(item != tab){
					                items.push(item);        
				                }else{
				                	 item.bHide=false;
				                }
				           // }
				        }, this);
					 Ext.each(items, function(item){					    
				            item.bHide=true;
				            item.tab.hide();	
				     }, this);
					var btn_return = tabs.tabBar.queryById("btn_return");
					if(tab.prev && !tab.prev_hide){
						btn_return.show();
					}else{
						btn_return.hide();
					}
				});
			}
		});	

       tabPanel.on('beforeremove', function(tabs, tab) {
	        //tabs.hideTabStripItem(tab.hide());
       		tab.tab.hide();
	        layout.hide_subscribe(tab.prs);
	        tab.bHide=true;
	        //关闭当前页
	        if(tab==tabs.getActiveTab()){
	        	for(var i=tabs.tps.length-1; i>=0; i--){
	        		var tc = tabs.tps[i];
	        		if(!tc.bHide){
	        			tc.tab.show();
	        			tabs.setActiveTab(tc);
	        			break;
	        		}
	        	}
	        }
	        return false;
		});	
		var tbar = new Ext.Toolbar(this.buildToolbar());     
		this.tbar = tbar;
        var viewport = new Ext.Viewport({
            layout: 'border',
            items: [
				tbar,{
                region: 'west',
                id: 'west-panel', // see Ext.getCmp() below
                title: '功能导航',
                split: true,
                width: 200,
                minSize: 175,
                maxSize: 400,
                collapsible: true,
                margins: '0 0 0 5',
                layout: {
                    type: 'accordion',
                    animate: true
                },
                items:this.items
            },tabPanel
            ]
        });
        this.viewport = viewport;

		this.tabVersion= tabPanel.add({
			icon:'icons/play.png',
			bodyStyle:'padding:10px;font-size:12px;',
            title: '公告栏',
           // bodyStyle:"background-image:url('icons/bk5.png');background-repeat: no-repeat;background-attachment: fixed;background-position: right bottom; ",
            contentEl: 'tabs_about',
           	closable:true,
            autoDestroy: false,
			autoScroll: true		
        }).show();
     }
});


var layout;
/*var grant_opts=[["无",0],["全部",1]];*/

Ext.onReady(function(){
	if(document.body.clientWidth<=1366){
		document.body.style.background = "url('wp3.jpg')";
	}else{
		document.body.style.background = "url('wp0.jpg')";
	}
	document.title=CFG.app_name;
	Ext.get("h1_title").setHTML(CFG.app_name);
	Ext.QuickTips.init();
	Ext.tip.QuickTipManager.init();
// Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	jsonrpc = new JSONRpcClient(CFG.app_ctx+"JSON-RPC");

   var its_grant=[]; 
   layout = New(THLayout,[its_grant]);
var func_succ=function(grants){
function menujson(){
	var menudata;
	Ext.Ajax.request({
		   type: "ajax",
		   async : false,
		   url:"json/mb_xgqx.json",
		   success: function(response, options){
				 var jsondata=eval(response.responseText);
				 menudata=jsondata;				
			   }
	});
	return menudata;
};	
function getFristMenu(){
	var qxmenu="";
	var menuStr=grants[5].split(";");
	for(var i=0; i<menuStr.length; i++){
		if(menuStr[i].indexOf("#")>=0){
			if(qxmenu.indexOf(menuStr[i].split("#")[0])==-1){
				qxmenu+=menuStr[i].split("#")[0]+";";
			}			
		}
	}
	return qxmenu;
	
}
function getSecondMenu(){
	var qxmenu="";
	var menuStr=grants[5].split(";");
	for(var i=0; i<menuStr.length; i++){
		if(menuStr[i].indexOf("#")>=0){
			qxmenu+=menuStr[i].split("#")[1]+";";
		}
	}
	return qxmenu;
}

creatTree();
function creatTree(){
	var menudata=menujson();
	var secondMenu=getSecondMenu();
	var qxmenu=getFristMenu();
	var qxmenuStr=qxmenu.split(";");
	for(var i=0;i<qxmenuStr.length;i++){
		for(var a=0;a<menudata.length;a++){
			if(menudata[a].text==qxmenuStr[i]){	
				var obj=[];
				for(var b=0;b<menudata[a].children.length;b++){					
					if(secondMenu.indexOf(menudata[a].children[b].text)>=0){
						obj.push(menudata[a].children[b]);	
					}				
				}
				
				its_grant[its_grant.length]=layout.buildTree(obj,"itr_"+a,qxmenuStr[i],menudata[a].menuImg);				
			}
		}		
	}	
}
   layout.show();
	if(layout.user_mnu.indexOf('招聘管理#数据集')!=-1)
		 layout.selectNode("招聘管理","数据集");
	else
		layout.selectNode("我的数据集","查看数据集");
   Bat.init(layout);
   if(!layout.b_debug){
	   confirm_leaving();
   }
   
 //直接关闭浏览器时通知服务注销
// beforeunload unload
/* Ext.EventManager.on(window, 'beforeunload', function(){
  Ext.MessageBox.wait('正在注销，请稍候...');
  var req={"map":layout.usr_info,"javaClass":"java.util.HashMap"};
  //此处必须用同步方式请求
  var data =  jsonrpc.BH.handle('O',req,'UMService');
    Bat.close_win_all();
   Ext.MessageBox.hide();
 }
 ); */
 
 bReadyOk=1;
 Ext.get("div_title").setOpacity(0.8,true);
  };
  var dologin = function(){
      bUM = decodeURIComponent(window.location.search);
      if(bUM=='?cas=true'){
	        var cookie_user;
	        for(var i=0; i<5; i++){
	           cookie_user = readCnCookie('COOKIE_USER');
	           if(cookie_user)
	             break;
	        }

			if(cookie_user){ // "cn=110108198103096884"
	           // Bat.gvs.wf_user = cookie_user;
				//Bat.gvs.wf_role=readCnCookie('COOKIE_ROLE');
				//debugger;
				if(!Bat.gvs){
					Bat.gvs={};
				}
	            Bat.gvs.wf_userName= readCnCookie('COOKIE_UN'); //郭珽          
	            Bat.gvs.wf_un = Bat.gvs.wf_userName+'['+cookie_user+']';
	            //THLayout.dowithLogin
	            //dowithLogin([[readCnCookie('COOKIE_ROLE'),
	           // readCnCookie('COOKIE_OBJ'),
	           // readCnCookie('COOKIE_FUNC')]],cookie_user);
	            //loginsucc();
	            var group_name = readCnCookie('COOKIE_ROLE'); //DEV
	            var Count="0";	            
	            var UserHandle ="";
	            var Name = readCnCookie('COOKIE_UN'); 
	            //待调试 id 为null 
	            var id= readCnCookie('COOKIE_USER_ID');  //usr.getId();
	            
	            var func = readCnCookie('COOKIE_FUNC'); //8  
	            var data = [group_name,Count,UserHandle,Name,id,func];//[DEV,0,cf299999999,sysroot1,Id]
	            /*
	            if (func){
		            var arrfunc = func.split(";");
		            for (var k=0;k<arrfunc.length;k++){
		            	data[data.length]=arrfunc[k];
		            }
				}*/
	            
	            layout.welcome_text="<span >欢迎您,<img src=\"icons/user.png\"></img><b>"+data[3]+"</b>&nbsp;&nbsp;&nbsp;</span>";
	            var ps={};
	            ps.user=cookie_user;
	   			layout.usr_info=ps;
	   			layout.usr_grant=data;
	   			layout.user=data[4];
	   			layout.user_name=data[3];
	   			layout.user_mnu=data[5];
	   			layout.usrId = cookie_user;
	   			//loginwin.hide(); 		   			            
	            func_succ(data);
			}else{
				Cookies.clear('COOKIE_OBJ');
				Cookies.clear('COOKIE_FUNC');
				Cookies.clear('COOKIE_USER');
				Cookies.clear('COOKIE_ROLE');
				Cookies.clear('COOKIE_UN');
				Cookies.clear('COOKIE_USER_ID');
				document.location='/zpn/servlet/authenticate?';
			}
        }else{
      	if(bUM.indexOf('?iam')==0){
      	    CC.login(loginsucc,login_f,bUM);
      	}
      	else if(bUM=='?zmhm'){
      	    CC.login(loginsucc,login_f);
      	}
      	else if(bUM=='?hhdd'){
      		Bat.gvs.wf_user = 'dev';
				Bat.gvs.wf_role='dev';
	            Bat.gvs.wf_userName= '开发人员';
	            Bat.gvs.wf_un = Bat.gvs.wf_userName+'['+cookie_user+']';
	           // bCCDebug=true;
	            CC.dowithLogin([['ps.user','','SYS_WEBSITE']],'dev');
      		loginsucc();
      	}
      	else	{
      		Ext.MessageBox.alert('登录说明', '招聘系统已纳入统一用户认证，系统将引导您登录。', function(btn){
      		  document.location='/zpn/servlet/authenticate?';
      		});
      		
      	}
      }
      };
  //分析url是否包含测试信息
  var para = decodeURIComponent(window.location.search);
  var pos_user = para.indexOf("user=");
  var pos_pwd = para.indexOf("&pwd=");
  if(pos_user!=-1){
  	var userId = para.substring(pos_user+5,pos_pwd);
  	var pwd = para.substring(pos_pwd+5);
  	layout.login(func_succ,userId,pwd);
  }
  else{  
     setTimeout(dologin,200);
  }
});

//处理键盘消息
if ('onhelp' in window) {   // Internet Explorer
    window.onhelp = function(){
   		 return layout.onhelp();
    };
}
else {  // Firefox, Opera, Google Chrome and Safari
    window.onkeydown = OnKeyDown;
}


function OnKeyDown (event) {
    if (event.keyCode == 112 /*KeyboardEvent.DOM_VK_F1*/) {
        return layout.onhelp();
    }
}

function confirm_leaving(){
	window_beforeUnload = function(e) {
	    var message = layout.user_name;
	    e = e || e.event;
	    if (e) {
	        e.returnValue = message;
	    }
	    return message;
	};
	
	window_unload = function(e) {
	};
	
	if (window.addEventListener) {
	    window.addEventListener('beforeunload', window_beforeUnload, false);
	} else if (window.attachEvent) {
	    window.attachEvent('onbeforeunload', window_beforeUnload);
	} else {
	    throw "Cannot attach event handler";
	}
	
	if (window.addEventListener) {
	    window.addEventListener('unload', window_unload, false);
	} else if (window.attachEvent) {
	    window.attachEvent('onunload', window_unload);
	} else {
	    throw "Cannot attach event handler";
	}
}
;

//cas begin
var Cookies = {};
Cookies.setAge = function(name,days){
    var jck= Cookies.get(name);
    var exp  = new Date(); 
    exp.setTime(exp.getTime() + days*24*60*60*1000);  
    Cookies.set('JSESSIONID',jck,exp);
};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    Cookies.set(name,"");
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};
function readCnCookie(name){ //中文cookie
	var strReturn = null;
	var tmp,reg=new RegExp("(^| )"+name+"=\"*([^;|^\"]*)(|;|$)","gi");
	if(tmp=reg.exec(document.cookie)){
		strReturn=decodeURIComponent(tmp[2]);
	}
	return strReturn;
} ;

